package com.example.administrator.test1;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import org.apache.http.client.ClientProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

public class GetCourse
{
    String cookie = "";
    static GetCourse spi = new GetCourse();

    public GetCourse()
    {

    }

    static
    {
        spi.getIndex();
    }

    public void main(String[] args)
    {
        Scanner sca = new Scanner(System.in);


        List<String> tlist = spi.getIndex();

        // 获取验证码
        spi.getImage();

        //学年学期
        String urlRoot = "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx";
        Map<String, String> map1 = new HashMap<String, String>();

        map1 = getGrade();
        System.out.println("学期：");
        System.out.println(map1);

        System.out.println("输入学期号");
        String tid = sca.next();

        //获取教师姓名
        String urlTeacher = "http://jw.zzti.edu.cn/ZNPK/Private/List_JS.aspx?xnxq=" + tid + "&js=";
        Map<String, String> map2 = new HashMap<String, String>();
        map2 = getTeacherList(urlTeacher);
        System.out.println(map2);
        System.out.println("输入教师号");
        String teaid = sca.next();

        System.out.println("输入验证码");

        //纪录星期
        int col = 1;
        String code = sca.next();
        Map<Integer, List> cmap = spi.sendPost(tid, teaid, code);
        if (cmap != null)
            for (Entry<Integer, List> l : cmap.entrySet())
            {
                int time = 1;
                System.out.println("星期" + (col++) + ":");
                for (Object o : l.getValue())
                {
                    System.out.println((time++) + ":" + o.toString());
                }
            }
        else
            System.out.println("错误");
    }

    public List<String> getIndex()
    {
        try
        {
            URL url = new URL("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Map<String, List<String>> map = conn.getHeaderFields();
            cookie = map.get("Set-Cookie").get(0);
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            String index = builder.toString();
            reader.close();
            conn.disconnect();

            Document doc = Jsoup.parse(index);
            Elements elements = doc.select("select[name=\"Sel_XNXQ\"] option");
            List<String> termList = new ArrayList<>();
            for (Element element : elements)
            {
                String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
                termList.add(t);
            }

            return termList;

        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // 发送请求 把学期 老师 验证码发送过去
    public Map<Integer, List> sendPost(String termId, String tid, String code)
    {
        try
        {
            URL url = new URL("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB_rpt.aspx");
            String param = "Sel_XNXQ=" + termId + "&Sel_JS=" + tid + "&type=" + 1 + "&txt_yzm=" + code;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36");
            conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
            conn.setRequestProperty("Referer", "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
            conn.setRequestProperty("Origin", "http://jw.zzti.edu.cn");
            conn.setRequestProperty("Cache-Control", "max-age=0");

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(param);
            dos.flush();
            dos.close();

            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            String info = builder.toString();

            Document doc = Jsoup.parse(info);
            Elements elements = doc.select("td");
            elements.get(0);

            Map<Integer, List> cmap = new LinkedHashMap<>();

            List<String> cl1 = new ArrayList<>();
            List<String> cl2 = new ArrayList<>();
            List<String> cl3 = new ArrayList<>();
            List<String> cl4 = new ArrayList<>();
            List<String> cl5 = new ArrayList<>();
            List<String> cl6 = new ArrayList<>();
            List<String> cl7 = new ArrayList<>();

            cmap.put(1, cl1);
            cmap.put(2, cl2);
            cmap.put(3, cl3);
            cmap.put(4, cl4);
            cmap.put(5, cl5);
            cmap.put(6, cl6);
            cmap.put(7, cl7);

            for (Element week : elements)
            {
                if (week.html().equals("星期一"))
                {
                    Element wtr = week.parent();
                    Elements trs = wtr.siblingElements();
                    for (int j = 0; j < trs.size(); j++)
                    {

                        Element tr = trs.get(j);
                        Elements trds = tr.children();
                        int ncounter = 0;
                        for (int i = 0; i < trds.size(); i++)
                        {
                            Element td = trds.get(i);

                            if (td.attr("valign").equals("top"))
                            {
                                if (td.text() != null)
                                    cmap.get(i - ncounter + 1).add(td.text() + "");
                                else
                                    cmap.get(i - ncounter + 1).add("");
                            } else
                                ncounter++;
                        }
                    }
                    return cmap;
                }
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;

    }

    public void getImage()
    {
        try
        {
            System.out.println("getImage。。。。");
            URL url = new URL("http://jw.zzti.edu.cn/sys/ValidateCode.aspx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Referer", "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
            InputStream in = conn.getInputStream();
            File file = new File("image.jpg");
            if (!file.exists())
            {
                file.createNewFile();
            }
            FileOutputStream fo = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1)
            {
                fo.write(buf, 0, length);

            }
            in.close();
            fo.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    public Map<String, String> getGrade()
    {
        Map<String, String> map = new HashMap<String, String>();
        try
        {
            String url = "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx";
            Document document = Jsoup.connect(url).get();
            Elements elements = document.select("[name=Sel_XNXQ] > option");
            for (Element e : elements)
            {
                map.put(e.attr("value"), e.text());
            }

        } catch (IOException e)
        {
            e.printStackTrace();
        }
        System.out.println(map);
        return map;
    }

    // 获取全部教师
    public Map<String, String> getTeacherList(String tid)
    {
        Map<String, String> map = null;
        try
        {
            String urlTeacher = "http://jw.zzti.edu.cn/ZNPK/Private/List_JS.aspx?xnxq=" + tid + "&js=";
            map = new HashMap<String, String>();
            Document document = Jsoup.connect(urlTeacher).get();
            String str = document.select("script").get(0).data();
            Document doc1 = Jsoup.parse(str);
            Elements elements = doc1.getElementsByTag("select").select("[name=Sel_JS] > option");
            System.out.println("教师：");
            for (Element e : elements)
            {
                map.put(e.attr("value"), e.text());
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        System.out.println(map);
        return map;

    }


    public Bitmap getImageByUrl()
    {
        String imgUrl = "";
        try
        {
            System.out.println("getImageByUrl....");
            String rootUrl = "http://jw.zzti.edu.cn";
            String url = "http://jwweb.fjny.edu.cn:8081/ZNPK/TeacherKBFB.aspx";
            Document doc2 = Jsoup.connect(url).get();
            Element element2 = doc2.getElementById("imgCode");
            String img1 = element2.attr("src");
            int strLen = img1.length();
            img1 = img1.substring(strLen - (strLen - 2), img1.length());
            imgUrl = rootUrl + img1;
            System.out.println("9999:"+imgUrl);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return getBitmapFromServer(imgUrl);
    }

    // 根据图片的url地址，解析出位图
    public static Bitmap getBitmapFromServer(String imagePath)
    {
        // HttpGet对象,注意参数为图片的地址。
        HttpGet httpRequest = new HttpGet(imagePath);
        Bitmap img = null;
        try
        {
            // HttpClient对象
            HttpClient client = new DefaultHttpClient();
            // 获得HttpResponse对象
            HttpResponse response = client.execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                img = BitmapFactory.decodeStream(is); // 关键是这句代码
            }

        } catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return img;
    }

}
